/**
 * Internationalization (i18n) utility
 * Supports multiple languages with fallback to English
 */

import enTranslations from './locales/en.json'
import zhCNTranslations from './locales/zh-CN.json'
import zhTWTranslations from './locales/zh-TW.json'

const translations = {
  en: enTranslations,
  'zh-CN': zhCNTranslations,
  'zh-TW': zhTWTranslations
}

let currentLanguage = 'zh-CN'

/**
 * Set the current language
 * @param {string} lang - Language code (e.g., 'en', 'zh-CN', 'zh-TW')
 */
export function setLanguage (lang) {
  if (translations[lang]) {
    currentLanguage = lang
  } else {
    // Fallback to English if language not found
    currentLanguage = 'en'
  }
}

/**
 * Get the current language
 * @returns {string} Current language code
 */
export function getLanguage () {
  return currentLanguage
}

/**
 * Translate a key to the current language
 * @param {string} key - Translation key (supports dot notation, e.g., 'menu.file.new')
 * @param {object} params - Optional parameters for interpolation
 * @returns {string} Translated string or the key if translation not found
 */
export function t (key, params = {}) {
  const keys = key.split('.')
  let translation = translations[currentLanguage] || translations.en

  // Navigate through nested object
  for (const k of keys) {
    if (translation && translation[k]) {
      translation = translation[k]
    } else {
      // Fallback to English
      translation = translations.en
      for (const k2 of keys) {
        if (translation && translation[k2]) {
          translation = translation[k2]
        } else {
          return key // Return key if translation not found
        }
      }
      break
    }
  }

  // If translation is a string, interpolate parameters
  if (typeof translation === 'string') {
    return translation.replace(/\{\{(\w+)\}\}/g, (match, paramKey) => {
      return params[paramKey] !== undefined ? params[paramKey] : match
    })
  }

  return typeof translation === 'string' ? translation : key
}

/**
 * Initialize i18n with a language
 * @param {string} lang - Language code
 */
export function initI18n (lang) {
  setLanguage(lang)
}

export default {
  setLanguage,
  getLanguage,
  t,
  initI18n
}
